package com.tietiao.filter;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tietiao.common.util.TietiaoUtil;


public class RandomImgServlet extends HttpServlet{
	private static final long serialVersionUID = 4847110949779070610L;
	private static final char[] AllChar =("ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
	private static final int width = 104;//图像宽度
	private static final int height = 40;//图像高度
	/**  
     * 生成的验证码以JPEG图片方式输出.  
     */  
    public void doGet(HttpServletRequest request, HttpServletResponse response)   
    			throws ServletException, IOException {
    	response.setContentType("image/jpeg");
    	ServletOutputStream sos = response.getOutputStream();
    	Random r = new Random();
		BufferedImage pic = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics gc = pic.getGraphics();
		gc.fillRect(0, 0, width, height);
		AffineTransform fontAT = new AffineTransform();//设置图形上下文环境字体
		Font font = new Font("Times New Roman",Font.CENTER_BASELINE,34);
		//随机产生30条干扰线条，使图像中的认证码不易被其他分析程序探测到
		gc.setColor(getRandColor(160, 200));
		for(int i=0;i<15;i++){
			int x1=r.nextInt(width/2);
			int y1=r.nextInt(height/2);
			int x2=r.nextInt(15);
			int y2=r.nextInt(15);
			gc.drawLine(x1, y1, x1+x2, y1+y2);
		}
		//随机产生100个干扰点，使图像中的验证码不易被其他分析程序探测到
		gc.setColor(getRandColor(120, 240));
		for(int i=0;i<50;i++){
			int x=r.nextInt(width);
			int y=r.nextInt(height);
			gc.drawOval(x, y, 2, 2);
		}
		String rs="";
		String rn="";//随机产生4个数字的验证码
		for(int i=0;i<4;i++){
			int rotate = r.nextInt(20);
			fontAT.rotate(r.nextBoolean() ? Math.toRadians(rotate):-Math.toRadians(rotate/2));
			gc.setFont(font.deriveFont(fontAT));
			rn = String.valueOf(AllChar[r.nextInt(26)]);
			rs +=rn;
			gc.setColor(new Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));
			gc.drawString(rn, 22*i+6,30);
		}
		gc.dispose();//释放图形上下文环境
		request.getSession().setAttribute(TietiaoUtil.RANDOM_KEY, rs);
		ImageIO.write(pic, "JPEG", sos);//输出生成后的验证码图像到页面
		sos.flush();
		sos.close();
	}
    /**
     * 获得随机颜色
     * @param fc 小于255数
     * @param bc 小于255数
     * @return
     */
	private Color getRandColor(int fc,int bc){
		Random r=new Random();
		if(fc>255) fc=255;
		if(bc>255) bc=255;
		int red=fc+r.nextInt(bc-fc);//红
		int green=fc+r.nextInt(bc-fc);//绿
		int blue=fc+r.nextInt(bc-fc);//蓝
		return new Color(red,green,blue);
	} 
}
